<template>
    <div class="white-box">
        <title-more title="满减优惠设置" />
        <pub-panel title="满减优惠" tip="开启后，用户订单满多少元减多少元的优惠设置才能生效" bottom="20px">
            <template #right>
                <el-switch
                    v-model="switch_one"
                    width="72px"
                    size="large"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                    @change="(val) => changeSwitchPanel(val, 1)"
                />
            </template>
        </pub-panel>
        <pub-panel title="满减活动是否支持优惠券" tip="开启后，当用户订单金额满足条件时可在满减基础上再使用优惠券" bottom="20px">
            <template #right>
                <el-switch
                    v-model="switch_two"
                    width="72px"
                    size="large"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                    @change="(val) => changeSwitchPanel(val, 2)"
                />
            </template>
        </pub-panel>
        <pub-panel title="凑单功能" tip="开启后，会员在购物车下单，当选择不满足满减活动时，会提示该会员凑单。活动关闭或过期该设置会失效。" bottom="20px">
            <template #right>
                <el-switch
                    v-model="switch_three"
                    width="72px"
                    size="large"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                    @change="(val) => changeSwitchPanel(val, 3)"
                />
            </template>
        </pub-panel>

        <div class="table-mb">
            <el-button type="primary" @click="clickUpdate(1)">添加活动</el-button>
        </div>
        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <el-table-column prop="title" label="活动名称"></el-table-column>
            <el-table-column label="订单金额">
                <template #default="{ row }">
                    <p class="table-price"><em>￥</em>{{ row.order_amount }}</p>
                </template>
            </el-table-column>
            <el-table-column label="优惠金额">
                <template #default="{ row }">
                    <p class="table-price"><em>￥</em>{{ row.coupon_amount }}</p>
                </template>
            </el-table-column>
            <el-table-column prop="s_time_label" label="生效时间"></el-table-column>
            <el-table-column prop="l_time_label" label="过期时间"></el-table-column>
            <el-table-column label="状态">
                <template #default="{ row }">
                    <el-switch
                        v-model="row.reward_status"
                        width="72px"
                        size="large"
                        inline-prompt
                        active-text="已开启"
                        inactive-text="已关闭"
                        :active-value="0"
                        :inactive-value="1"
                        @change="(val) => changeSwitch(val, row)"
                    />
                </template>
            </el-table-column>
            <el-table-column label="操作" width="170" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" class="theme-btn" @click="clickUpdate(2, row)">编辑</el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 添加/编辑 -->
        <el-dialog
            v-model="dialogClass"
            :title="class_type == 1 ? '添加活动' : '编辑活动'"
            width="580px"
            :append-to-body="true"
            :destroy-on-close="true"
            :close-on-click-modal="false"
            @close="closeClass"
        >
            <el-form ref="ruleClassRef" :model="ruleClassForm" :rules="ruleCheckClass" label-width="120px">
                <el-form-item label="活动名称" prop="title">
                    <el-input v-model.trim="ruleClassForm.title" clearable placeholder="请输入活动名称" />
                </el-form-item>
                <el-form-item label="订单金额" prop="order_price">
                    <el-input v-model.trim="ruleClassForm.order_price" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入订单金额" />
                    <p class="input-tips">当支付金额<code>≥</code>订单金额时，即视为满足条件</p>
                </el-form-item>
                <el-form-item label="优惠金额" prop="price">
                    <el-input v-model.trim="ruleClassForm.price" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入优惠金额" />
                    <p class="input-tips">当条件满足时，可在原价格基础上减去优惠金额</p>
                </el-form-item>
                <el-form-item label="生效时间" prop="start_time">
                    <el-date-picker
                        v-model="ruleClassForm.start_time"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择生效时间"
                    />
                </el-form-item>
                <el-form-item label="过期时间" prop="end_time">
                    <el-date-picker
                        v-model="ruleClassForm.end_time"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择过期时间"
                    />
                </el-form-item>
                <el-form-item label="生效状态" prop="status">
                    <el-switch
                        v-model="ruleClassForm.status"
                        width="72px"
                        size="large"
                        inline-prompt
                        :active-value="0"
                        :inactive-value="1"
                        active-text="已开启"
                        inactive-text="已关闭"
                    />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitForm(ruleClassRef)"> 确认 </el-button>
                        <el-button @click="resetForm(ruleClassRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, watch, onBeforeUnmount } from "vue"
import OneLoad from "@mixins/one-load"
import GoBack from "@components/GoBack.vue"
import TitleMore from "@components/title-more.vue"
import PubPanel from "@components/PubPanel.vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getConfig()
})

onBeforeUnmount(() => {})

const switch_one = ref(false) // 是否开启活动
const switch_two = ref(false) // 是否支持优惠券
const switch_three = ref(false) // 是否开启满减凑单
function getConfig() {
    proxy.$axios
        .get("ump/reward/index", {
            params: {
                action: "config",
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                switch_one.value = result.reward_price == 0 ? false : true
                switch_two.value = result.reward_price_coupon == 0 ? false : true
                switch_three.value = result.reward_price_add == 0 ? false : true
                getList()
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
// 设置配置
const changeSwitchPanel = (val, type) => {
    let field = ""
    if (type == 1) {
        field = "reward_price"
    } else {
        field = type == 2 ? "reward_price_coupon" : "reward_price_add"
    }
    proxy.$axios
        .get("ump/reward/index", {
            params: {
                action: "config_set",
                field,
                field_val: val ? 1 : 0,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                proxy.$message({ message: "设置成功", type: "success" })
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, pubParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        action: "index",
    }
    getdata("ump/reward/index", params)
}

/**
 * 添加/编辑
 * @param {Boolean} dialogClass 添加/编辑弹窗状态
 * @param {Boolean} form_loading 提交按钮状态
 * @param {Number} class_type 1是添加，2是编辑
 * @param {Array} ruleClassRef 表单规则
 * @param {Object} ruleClassForm  表单字段
 * @param {Object} ruleCheckClass  表单提示
 * @param {Function} submitForm 提交表单
 * @param {Function} closeClass 关闭弹窗
 */
const dialogClass = ref(false)
const class_type = ref(1)
const form_loading = ref(false)
const ruleClassRef = ref(null)
const ruleClassForm = reactive({
    id: "",
    title: "",
    price: "",
    order_price: "",
    start_time: "",
    end_time: "",
    status: 0,
})
const ruleCheckClass = reactive({
    title: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
    order_price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    start_time: [{ required: true, message: "请选择生效时间", trigger: "change" }],
    end_time: [{ required: true, message: "请选择过期时间", trigger: "change" }],
    status: [{ required: true, message: "请选择生效状态", trigger: "blur" }],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                title: ruleClassForm.title,
                order_amount: ruleClassForm.order_price,
                coupon_amount: ruleClassForm.price,
                s_time: ruleClassForm.start_time,
                l_time: ruleClassForm.end_time,
                reward_status: ruleClassForm.status, // 活动状态[0:启用,1:关闭]
            }
            if (class_type.value == 2) {
                data.reward_id = ruleClassForm.id
            }
            let url = class_type.value == 1 ? "ump/reward/add" : "ump/reward/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogClass.value = false
                        proxy.$message({ message: `${class_type.value == 1 ? "添加成功！" : "编辑成功！"}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeClass = () => {
    dialogClass.value = false
    resetForm(ruleClassRef.value)
}
const clickUpdate = (type, row) => {
    class_type.value = type
    dialogClass.value = true
    if (type == 2) {
        setTimeout(() => {
            class_type.value = 2
            ruleClassForm.id = row.reward_id
            ruleClassForm.title = row.title
            ruleClassForm.order_price = row.order_amount
            ruleClassForm.price = row.coupon_amount
            ruleClassForm.start_time = row.s_time_label
            ruleClassForm.end_time = row.l_time_label
            ruleClassForm.status = row.reward_status
        }, 50)
    }
}

const clickDel = (row) => {
    proxy.$axios
        .post("ump/reward/delete", {
            reward_id: row.reward_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

// 列表满减开启/关闭
const changeSwitch = (val, row) => {
    proxy.$axios
        .post("ump/reward/status", {
            reward_id: row.reward_id,
            status: val,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "FullDiscount",
}
</script>

<style lang="less" scoped>
.table-price {
    font-size: @font-size-md;
    em {
        font-size: 13px;
    }
}
</style>
